<!--
 * @Description:
 * @Author: william
 * @Date: 2025-02-17 16:47:40
 * @LastEditors: william
 * @LastEditTime: 2025-04-14 09:29:43
-->
<template>
  <el-cascader
    v-model="ids"
    :placeholder="getPlaceholder()"
    :options="deptOptions"
    :props="deptProps"
    :clearable="clearable"
    :="$attrs"
    @clear="handleClear"
  />
</template>

<script setup>
const props = defineProps({
  // 上级部门的id
  deptId: {
    type: String,
    default: ''
  },
  placeholder: {
    type: String,
    default: ''
  },
  clearable: {
    type: Boolean,
    default: true
  },
  label: {
    type: String,
    default: ''
  },
  type: {
    type: String,
    default: 'view' // view:查看，edit:编辑
  }
})

const ids = defineModel({
  type: Array,
  default: []
})
const id = defineModel('id', {
  type: String,
  default: ''
})

const deptOptions = ref([])
const deptProps = {
  checkStrictly: true,
  children: 'childDeptList'
}

watch(
  [() => id.value, () => deptOptions.value],
  nv => {
    if (nv[0] && nv[1].length) {
      // 设置cascader的值
      let path = findPathById(deptOptions.value)
      if (!path.length) path = [id.value]
      if (props.type === 'edit') path = path.slice(0, -1)
      ids.value = path
    }
  },
  {
    deep: true
  }
)

onMounted(() => {
  getCascaderList()
})

const getCascaderList = _ => {
  deptOptions.value = []
  g_api.userCenter
    .apiDeptTreeList({
      tenantId: props.deptId
    })
    .then(({ code, data }) => {
      if (code === '200' && data) {
        deptOptions.value = data
      }
    })
}

// 循环递归查找树上符合条件的子节点和及其父节点
const findPathById = tree => {
  for (const node of tree) {
    const { deptId, childDeptList } = node // 显式解构使用 node 的属性
    if (deptId === id.value) {
      return [deptId]
    }
    if (childDeptList?.length) {
      const result = findPathById(childDeptList)
      if (result.length) return [deptId, ...result]
    }
  }
  return []
}

const getPlaceholder = _ => {
  return (
    props.placeholder ||
    g_rules.zhAndEnShowMsg(g_t('public.pleaseSelect'), props.label)
  )
}

const handleClear = _ => {
  nextTick(() => {
    ids.value = []
    id.value = ''
  })
}
</script>

<style scoped lang="scss"></style>
